<template>
  <div id="scene" @click="onClickModel"></div>
</template>

<script>
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

let scene;
let camera;
let renderer;
let controls;

let raycaster;
let mouse;
export default {
  data() {
    return {
      publicPath: process.env.BASE_URL,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    onClickModel(e) {
      // 通过鼠标点击位置,计算出 raycaster 所需点的位置,以屏幕为中心点,范围 -1 到 1
      mouse.x = ((e.clientX - 200) / (window.innerWidth - 200)) * 2 - 1; //左侧导航菜单width占了200px,计算时去除
      mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;

      //通过鼠标点击的位置和当前相机的矩阵计算出射线位置
      raycaster.setFromCamera(mouse, camera);

      // 获取与射线相交的对象数组，按照距离排序，越近的越靠前
      const intersects = raycaster.intersectObjects(this.mesh.children);

      if (intersects.length > 0) {
        let currentMesh = intersects[0].object;
      }
    },
    // 初始化
    init() {
      this.createScene(); // 创建场景
      this.createLight(); // 创建光源
      this.createCamera(); // 创建相机
      this.createRender(); // 创建渲染器
      this.createControls(); // 创建控件对象
      this.render(); // 渲染
    },
    // 创建场景
    createScene() {
      scene = new THREE.Scene();

      scene.add(new THREE.AxesHelper(20));

      // 声明 raycaster 和 mouse 变量
      raycaster = new THREE.Raycaster();
      mouse = new THREE.Vector2();
    },
    // 创建光源
    createLight() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.1); // 创建环境光
      scene.add(ambientLight); // 将环境光添加到场景

      const spotLight = new THREE.SpotLight(0xffffff); // 创建聚光灯
      spotLight.position.set(0, 20, 30);
      spotLight.castShadow = true;
      scene.add(spotLight);
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById("scene");
      camera = new THREE.PerspectiveCamera(
        35,
        element.clientWidth / element.clientHeight,
        0.1,
        1000
      );
      camera.position.set(0, 0, 8); // 设置相机位置
      camera.lookAt(scene.position);
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById("scene");
      renderer = new THREE.WebGLRenderer();
      renderer.setSize(element.clientWidth, element.clientHeight); // 设置渲染区域尺寸
      renderer.shadowMap.enabled = true; // 显示阴影
      renderer.shadowMap.type = THREE.PCFSoftShadowMap;
      renderer.setClearColor(0xffffff, 0); // 设置背景颜色
      element.appendChild(renderer.domElement);
    },
    render() {
      renderer.render(scene, camera);
      requestAnimationFrame(this.render);
    },
    // 创建控件对象
    createControls() {
      controls = new OrbitControls(camera, renderer.domElement);
    },
  },
};
</script>
<style lang="less" scoped>
.model-operation {
  width: 100%;
  height: 100%;
  position: relative;
  #scene {
    width: 100%;
    height: 100%;
  }
  .change-btn {
    position: absolute;
    top: 20px;
    left: 20px;
  }
}
</style>